package com.ncbee.base.config.common;

import com.ncbee.base.model.vo.BaseQuery;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author fengzirong
 * @DESC
 * @Date 2018/11/29 14:05
 **/
@Configuration
public class CustomDatabind implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType().equals(BaseQuery.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        Map<String,Object> map=new HashMap<String,Object>();
        Enumeration em=request.getParameterNames();
        BaseQuery baseQuery=new BaseQuery();
        while(em.hasMoreElements()){
            String name=(String)em.nextElement();
            String value=request.getParameter(name);
            if("page".equals(name)){
                baseQuery.setPage(Long.parseLong(value));
            }
            if("limit".equals(name)){
                baseQuery.setLimit(Long.parseLong(value));
            }
            map.put(name,value);
        }
        //获取
        baseQuery.setParams(map);
        return baseQuery;
    }
}
